package com.xiaofu.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.xiaofu.config.OSSConfig;
import com.xiaofu.service.FileService;
import com.xiaofu.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadUserImg(MultipartFile file) {
        // 获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        // 创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        
        // 获取原生文件名
        String originalFilename = file.getOriginalFilename();
        
        // JDK8的日期格式
        LocalDateTime ldt = LocalDateTime.now();
        String folder = DateTimeFormatter.ofPattern("yyyyy/MM/dd").format(ldt);
        String fileName = CommonUtil.generateUUID();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 在OSS上的bucket下创建 user 的文件夹
        String newFileName = "user/" + folder + "/" + fileName + extension;
        PutObjectResult result = null;
        try {
            result = ossClient.putObject(bucketName, newFileName, file.getInputStream());
            // 拼接返回路径
            if (result != null) {
                return "https://" + bucketName + "." + endpoint + "/" + newFileName;
            }
        } catch (IOException e) {
            log.error("文件上传失败: {}",newFileName,e);
        }finally {
            // oss关闭服务,不然会造成OOM
            ossClient.shutdown();
        }
        return "";
    }
}
